/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2020 All Rights Reserved.
 */
package com.dal.flink;


import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @author dingaolin
 * @version : NcServer.java, v 0.1 2020年10月22日 下午2:17 dingaolin Exp $
 */
public class NcServer {
    // 定义端口号
    private static final int PORT = 9001;
    private static final int INTERVAL = 2000;

    public static void main(String[] args) throws Exception {
        start(PORT, INTERVAL);
    }

    private static void start(int port, int interval) throws Exception {
        ServerSocket server = new ServerSocket(port);
        Socket socket = server.accept();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("[" + simpleDateFormat.format(new Date()) + "]" + socket.getInetAddress() + "已建立连接！");

        // 后台线程监控连接是否断开
        new Thread(new CheckClientThread(socket)).start();

        // 输出流
        OutputStream outputStream = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(outputStream, true);

        // 模拟数据输出
        while (true) {
            Thread.sleep(interval);
            String content = MockStreamUtil.groupMockData();
            System.out.println("发送数据：" + content);
            pw.println(content);
        }
    }

    // 监控连接程序是否断开 线程类
    static class CheckClientThread implements Runnable {

        private Socket socketClient;

        public CheckClientThread(Socket socketClient) {
            this.socketClient = socketClient;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    socketClient.sendUrgentData(0xFF);
                } catch (IOException e) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println("[" + simpleDateFormat.format(new Date()) + "]" + socketClient.getInetAddress() + "连接已关闭！");
                    // 断开后退出程序
                    System.exit(0);
                }
            }
        }
    }
}